package com.bto.leasetest.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import com.bto.leasetest.utils.JsonRequestHelper;
import com.bto.leasetest.utils.LogUtils;
import com.bto.leasetest.utils.NullUtils;
import com.bto.leasetest.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
@RefreshScope
public class LeaseTestMonogoDbController {

    @Autowired
    private MongoTemplate mongoTemplate;


    @RequestMapping(value = "/**")
    public JSONObject handleGetRequest(ServletRequest request, ServletResponse response)  {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        //请求体中的参数（json参数）
        JSONObject requestBodyJSONObject = null;
        //请求方式
        String method = httpRequest.getMethod();
        //请求路径
        String path = httpRequest.getRequestURI();
        if (StringUtils.isNotBlank(path)) {
            path = path.replaceFirst("/lease","");
        }
        //请求参数
        String queryString = httpRequest.getQueryString();

        try {
            Map<String, Object> requestBody = JsonRequestHelper.getJsonBody(httpRequest);
            requestBodyJSONObject = JSONObject.parseObject(JSON.toJSONString(requestBody));
            LogUtils.requsetLogger.info("Request Args : {}", JSON.toJSONString(requestBodyJSONObject, JSONWriter.Feature.PrettyFormat));
        } catch (Exception e) {
            System.out.println("e = " + e);
        }

        
        // 获取请求参数
        Enumeration<String> parameterNames = httpRequest.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String paramName = parameterNames.nextElement();
            String paramValue = httpRequest.getParameter(paramName);
            System.out.println("Parameter: " + paramName + ", Value: " + paramValue);
        }
        JSONObject jsonObject = logRequest(requestBodyJSONObject, method, path);
        LogUtils.requsetLogger.info("返回值 logRequest返回体Request Args : {}", JSON.toJSONString(jsonObject, JSONWriter.Feature.PrettyFormat));
        System.out.println("jsonObject = " + jsonObject);
        return jsonObject;
    }

    //id可能是订单iD, 身份证ID等
    private JSONObject logRequest(JSONObject requestBodyJSONObject, String method, String path) {
        System.out.println("requestBodyJSONObject = " + requestBodyJSONObject);
        System.out.println("path = " + path);
        System.out.println("method = " + method);
        //and or 多条件查询
        Criteria criteria = new Criteria();
        //and 查询年龄大于2并且在广州是的人
        criteria.andOperator(Criteria.where("_id").is(path), Criteria.where("method").is(method));
        Query query = new Query(criteria);
        JSONObject jsonObject = mongoTemplate.findOne(query, JSONObject.class, "bto-order-lease-template");
//        JSONObject jsonObject = mongoTemplate.findOne(query, JSONObject.class, "bto-order-lease-template");
        LogUtils.requsetLogger.info("MongoDB查询 Args : {}", JSON.toJSONString(jsonObject, JSONWriter.Feature.PrettyFormat));

        System.out.println("jsonObject = " + jsonObject);
        if (NullUtils.isNotNull(jsonObject)) {
            //关系
            JSONObject relation = jsonObject.getObject("relation", JSONObject.class);
            //模板列表
            JSONObject template = jsonObject.getObject("template", JSONObject.class);
            if (NullUtils.isNotNull(relation)) {
                List<String> orderIds = relation.getJSONArray("orderIds").toJavaList(String.class);
                String templateName = relation.getString("templateName");
                boolean isHasId = relation.getBoolean("isHasId");

                String id = null;
                //如果isHasId为true则获取ID并且写入返回体中
                if (isHasId) {
                    id = getId(requestBodyJSONObject, path);
                }

                //如果orderIds为空符合所有的条件直接匹配模板ID
                if (NullUtils.isEmpty(orderIds)) {
                    return returnResponse(template, templateName, id, path);
                } else {
                    if (StringUtils.isNotBlank(id)) {
                        if (orderIds.contains(id)) {
                            return returnResponse(template, templateName, id, path);
                        }
                    } else {
                        return returnResponse(template, templateName, id, path);
                    }
                }
            }
        }

        return null;
    }


    private JSONObject returnResponse(JSONObject template, String templateName, String id, String path) {
        if (NullUtils.isNotNull(template) && StringUtils.isNotBlank(templateName)) {
            JSONObject jsonObject = template.getObject(templateName, JSONObject.class);
            if (StringUtils.isNotBlank(id)) {
                //设置ID到返回体中
                JSONObject jsonObjectHasId = setId(jsonObject, id, path);
                if (NullUtils.isNotNull(jsonObjectHasId)) {
                    return jsonObjectHasId;
                }
                return jsonObject;
            } else {
                return jsonObject;
            }
        }
        return null;
    }

    //设置ID到返回体中
    private JSONObject setId(JSONObject jsonObject, String id, String path) {
        //预审状态查询 -- 身份证ID设置到返回体
        if (path.equals("/r/api/finance/project/tenant/status/query")) {
            JSONArray body = jsonObject.getJSONArray("body");
            body.set(0 , jsonObject.getJSONArray("body").getJSONObject(0).fluentPut("idCardNo", id));
            jsonObject.put("body", body);
            return jsonObject;
        }
        //同步进件 || 查询进件状态 || 农户投放审查信息同步 || 并网及商务信息更新 || 租后购售电合同补充推送
        else if (path.equals("/r/api/finance/sync/project/operating/lease")
                || path.equals("/r/api/finance/project/operating/lease/status/query")
                || path.equals("/r/api/finance/sync/project/operating/lease/sign")
                || path.equals("r/api/finance/ol/sync/sign/update")
                || path.equals("/r/api/finance/ol/power/sell/file")
                || path.equals("r/api/gd/create/register/url/1")
                || path.equals("r/api/gd/create/register/url/2")
                || path.equals("/r/api/tenant/account/info/query")) {
            JSONArray body = jsonObject.getJSONArray("body");
            body.set(0 , jsonObject.getJSONArray("body").getJSONObject(0).fluentPut("businessKey", id));
            jsonObject.put("body", body);
            return jsonObject;
        }
        return jsonObject;
    }


    //获取请求体中关键ID
    private String getId(JSONObject requestBodyJSONObject, String path) {
        JSONArray body = requestBodyJSONObject.getJSONArray("body");
        JSONObject jsonObject = null;
        if (NullUtils.isNotEmpty(body)) {
            jsonObject = body.getJSONObject(0);
        }

        //预审状态查询 -- 获取身份证ID
        if (path.equals("/r/api/finance/project/tenant/status/query")) {
            if (NullUtils.isNotNull(jsonObject)) {
                return jsonObject.getString("idCardNo");
            }
        }
        //同步文件
        else if (path.equals("/r/api/finance/ol/sync/file")) {
            if (NullUtils.isNotNull(jsonObject)) {
                return jsonObject.getString("businessKey");
            }
        }
        //同步进件 || 农户投放审查信息同步 || 并网及商务信息更新 || 租后购售电合同补充推送
        else if (path.equals("/r/api/finance/sync/project/operating/lease")
                || path.equals("/r/api/finance/sync/project/operating/lease/sign")
                || path.equals("r/api/finance/ol/sync/sign/update")
                || path.equals("/r/api/finance/ol/power/sell/file")) {
            if (NullUtils.isNotNull(jsonObject)) {
                return jsonObject.getObject("prjProject", JSONObject.class).getString("partnersContractNumber");
            }
        }
        //查询进件状态
        else if (path.equals("/r/api/finance/project/operating/lease/status/query")) {
            if (NullUtils.isNotNull(jsonObject)) {
                return jsonObject.getObject("prjDocumentStatusDto", JSONObject.class).getString("partnersContractNumber");
            }
        }
        //获取合同文本
        else if (path.equals("/r/api/finance/contract/file/get")) {
            if (NullUtils.isNotNull(jsonObject)) {
                return jsonObject.getString("partnersContractNumber");
            }
        } else if (path.equals("/r/api/gd/create/register/url/1")
                || path.equals("/r/api/gd/create/register/url/2")) {
            if (NullUtils.isNotNull(jsonObject)) {
                return jsonObject.getString("certNo");
            }
        } else if (path.equals("/r/api/tenant/account/info/query")) {
            if (NullUtils.isNotNull(jsonObject)) {
                return jsonObject.getString("corpCommSerno");
            }
        }
        return null;
    }

}
